﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
using ADFunctions;

namespace PushEntitle
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            userStatus.Text = "Loggin in...........";
            
            string uname = textBox1.Text.ToString();
            string upass = maskedTextBox1.Text.ToString();
            string domain = "bhi-master";
            PE.Var.ADdomain = domain;
            PE.Var.ADpass = upass;
            PE.Var.ADuname = uname;
            //Exception ex = new Exception();
            //Check AD to see if User info is correct
            //Check to see if User is Tech 4            
            try
            {
                if (ADF.Authenticate(uname, upass, domain))
                {
                    userStatus.Text = "Checking Access Level...";
                    PrincipalContext pContext = new PrincipalContext(ContextType.Domain);
                    UserPrincipal userP = new UserPrincipal(pContext);
                    userP.SamAccountName = uname;
                    PrincipalSearcher pSearcher = new PrincipalSearcher();
                    pSearcher.QueryFilter = userP;
                    UserPrincipal uPrincipal = pSearcher.FindOne() as UserPrincipal;
                    if (ADF.CheckAdmin(uPrincipal))
                    {
                        userStatus.Text = "Access Granted!";
                        frmPushEntitle pe = new frmPushEntitle();
                        this.Hide();
                        pe.Show();

                    }
                    else
                    {
                        MessageBox.Show("Error");
                    }
                    //Check for Tech 4
                }
                else
                {
                    userStatus.Text = "Access Denied!";
                };
            }
            catch (Exception ex)
            {
                userStatus.Text = ex.Message;
            };
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
    }
}
